# -!-coding:utf-8-!-
# @Time: 2022/3/6
# @Dev: TJ

import os
import sys
import time
import requests
from requests import Response
from loguru import logger
from werkzeug.utils import import_string

hook_requests = None
monitor_path = os.path.join(os.path.split(__file__)[0], 'monitor.py')
if os.path.exists(monitor_path):
    sys.path.append(os.path.abspath(os.path.split(__file__)[0]))
    monitor = import_string('monitor')
    hook_requests = monitor.Monitor.requests


class ProxyChannel:
    CLOSE = ''  # 关闭代理

    DEFAULT = ''  # 默认代理


class SubRequests(ProxyChannel):
    DEFAULT_RESPONSE_CODE = 500  # 默认响应状态码

    def __init__(self):
        self.proxies = dict()

    def set_proxies(self, proxy=ProxyChannel.DEFAULT):
        """ 设置代理 默认使用内网负载均衡端口 """
        if proxy == self.CLOSE:
            self.proxies = dict()

        else:
            self.proxies.update({
                'http': proxy,
                'https': proxy,
            })

    def get(self, url, params=None, timeout=30, proxies=None, **kwargs):
        if not proxies:
            proxies = self.proxies

        try:
            response = requests.get(url=url, params=params, timeout=timeout, proxies=proxies,
                                    hooks=dict(response=[hook_requests]), **kwargs)
        except Exception as e:
            logger.error(f'SubRequests.get Exception: {e}')

            response = Response()
            response.url = url
            response.status_code = self.DEFAULT_RESPONSE_CODE

            if hook_requests:
                hook_requests(response)

        return response

    def post(self, url, data=None, json=None, timeout=30, proxies=None, **kwargs):
        if not proxies:
            proxies = self.proxies

        try:
            response = requests.post(url=url, data=data, json=json, proxies=proxies, timeout=timeout,
                                     hooks=dict(response=[hook_requests]), **kwargs)
        except Exception as e:
            logger.error(f'SubRequests.post Exception: {e}')

            response = Response()
            response.url = url
            response.status_code = self.DEFAULT_RESPONSE_CODE

            if hook_requests:
                hook_requests(response)

        return response


if __name__ == '__main__':
    r = SubRequests()
    r.set_proxies(SubRequests.DEFAULT)
    with open(f'requests_response_time.txt', 'a') as f:
        while True:
            logger.debug(r.proxies)
            s_time = time.time()
            resp = r.get('http://myip.ipip.net/')
            response_time = int((time.time() - s_time) * 1000)
            f.write(f'{resp} | 响应：{response_time} ms | {resp.text}\n')
            logger.info(f'{resp} | 响应：{response_time} ms | {resp.text}')
            time.sleep(1)
